function safeTemplateLiteral(str, context) {
  return str.replace(/\$\{([^}]*)\}/g, function (match, expr) {
    try {
      // 安全地从context中获取值，支持点符号访问属性
      const value = expr
        .split(".")
        .reduce((obj, key) => obj && obj[key], context);
      return typeof value === "function" ? value.call(context) : value;
    } catch (e) {
      // 如果求值失败，则返回原始的占位符文本
      return match;
    }
  });
}

// 示例用法：
const context = {
  name: "Alice",
  age: 25,
  greet: function () {
    return `Hello, ${this.name}!`;
  },
};

const templateString =
  "My name is ${name}, and I am ${age} years old. Greeting: ${greet()}";
console.log(safeTemplateLiteral(templateString, context));
